package action

import (
	"../global"
	"../model"
	"crypto/md5"
	"encoding/hex"
	"github.com/astaxie/beego/httplib"
	"github.com/go-pg/pg"
	"sort"
	"strconv"
	"strings"
)

//定义发起玄缈代付请求返回结构体
type WithdrawReturn struct {
	Respcd  string `json:"respcd"`
	Respmsg string `json:"respmsg"`
	Data    struct {
		CashStatus int    `json:"cash_status"`
		Sign       string `json:"sign"`
		Platcode   string `json:"platcode"`
		BizSn      string `json:"biz_sn"`
		OutSn      string `json:"out_sn"`
		CashMsg    string `json:"cash_msg"`
	}
}

//定义玄缈代付状态查询返回结构体
type WithdrawQuery struct {
	Respcd  string `json:"respcd"`
	Respmsg string `json:"respmsg"`
	Data    struct {
		Fee        int    `json:"fee"`
		CashStatus int    `json:"cash_status"`
		Sign       string `json:"sign"`
		Platcode   string `json:"platcode"`
		BizSn      string `json:"biz_sn"`
		OutSn      string `json:"out_sn"`
		CashMsg    string `json:"cash_msg"`
	}
}

//根据传参返回用户ID
func GetUserID(paramName string, value string) int64 {
	var UserModel model.UserModel
	switch paramName {
	case "mobile":
		if user, err := UserModel.GetUser(&model.User{Mobile: value}, []string{"id"}, &model.ListParams{Limit: 1}); err == nil {
			if len(user) != 0 {
				return user[0].ID
			}
		}
		return 0
	case "nickname":
		if user, err := UserModel.GetUser(&model.User{NickName: value}, []string{"id"}, &model.ListParams{Limit: 1}); err == nil {
			if len(user) != 0 {
				return user[0].ID
			}
		}
		return 0
	case "fullname":
		if user, err := UserModel.GetUser(&model.User{FullName: value}, []string{"id"}, &model.ListParams{Limit: 1}); err == nil {
			if len(user) != 0 {
				return user[0].ID
			}
		}
		return 0
	}
	return 0
}

//充值提现数据统计
func DataCount(tableName string, startTime int64, endTime int64) interface{} {
	var Count int64
	result := make(map[string]int64)
	//已完成订单总数
	if _, err := global.DB.Query(&Count,
		`SELECT count(*) FROM "`+tableName+`" WHERE status = ? AND start_time >= ? AND end_time <= ?`,
		true, startTime, endTime); err == nil {
		result["success_"+tableName+"_count"] = Count
	}
	//已完成订单总额
	if _, err := global.DB.Query(&Count, `SELECT sum("amount") FROM "`+tableName+`" WHERE status = ? AND start_time >= ? AND end_time <= ?`,
		true, startTime, endTime); err == nil {
		result["success_"+tableName+"_amount"] = Count

	}
	//未完成订单总数
	if _, err := global.DB.Query(&Count, `SELECT count(*) FROM "`+tableName+`" WHERE status = ? AND start_time >= ? AND end_time <= ?`,
		false, startTime, endTime); err == nil {
		result["unsuccess_"+tableName+"_count"] = Count

	}
	//未完成订单总额
	if _, err := global.DB.Query(&Count, `SELECT sum("amount") FROM "`+tableName+`" WHERE status = ? AND start_time >= ? AND end_time <= ?`,
		false, startTime, endTime); err == nil {
		result["unsuccess_"+tableName+"_amount"] = Count
	}
	return result
}

//根据用户ID或所需要获取的内容返回对应数据
func GetData(ID int64, ModelName string, SearchTime1 int64, SearchTime2 int64) interface{} {
	switch ModelName {
	case "OrderTradeCompletedModel":
		var Model model.OrderTradeCompletedModel
		res, err := Model.GetOrder(&model.OrderTradeCompleted{UserID: ID, BuyTime: SearchTime1, SellTime: SearchTime2}, []string{}, &model.ListParams{})
		if err != nil {
			if err == pg.ErrNoRows {
				global.Logger.Error("用户历史购买记录不存在：" + err.Error())
				return false
			} else {
				global.Logger.Error("查询用户购买记录出错：" + err.Error())
				return false
			}
		}
		if len(res) == 0 {
			return ""
		}
		return &res
	case "OrderTradeInCompleteModel":
		var Model model.OrderTradeInCompleteModel
		res, err := Model.GetOrder(&model.OrderTradeInComplete{UserID: ID}, []string{}, &model.ListParams{})
		if err != nil {
			if err == pg.ErrNoRows {
				global.Logger.Error("用户持仓订单不存在：" + err.Error())
				return false
			} else {
				global.Logger.Error("查询用户持仓订单出错：" + err.Error())
				return false
			}
		}
		if len(res) == 0 {
			return ""
		}
		return &res
	case "RechargeOrderModel":
		var Model model.RechargeOrderModel
		res, err := Model.GetOrder(&model.RechargeOrder{UserID: ID, StartTime: SearchTime1, EndTime: SearchTime2}, []string{}, &model.ListParams{})
		if err != nil {
			if err == pg.ErrNoRows {
				global.Logger.Error("用户历史购买记录不存在：" + err.Error())
				return false
			} else {
				global.Logger.Error("查询用户购买记录出错：" + err.Error())
				return false
			}
		}
		if len(res) == 0 {
			return ""
		}
		return &res
	case "WithdrawOrderModel":
		var Model model.WithdrawOrderModel
		res, err := Model.GetOrder(&model.WithdrawOrder{UserID: ID, StartTime: SearchTime1, EndTime: SearchTime2}, []string{}, &model.ListParams{})
		if err != nil {
			if err == pg.ErrNoRows {
				global.Logger.Error("用户历史购买记录不存在：" + err.Error())
				return false
			} else {
				global.Logger.Error("查询用户购买记录出错：" + err.Error())
				return false
			}
		}
		if len(res) == 0 {
			return ""
		}
		return &res
	case "UserModel":
		var Model model.UserModel
		res, err := Model.GetUser(&model.User{ParentID: ID}, []string{"id", "nickname", "fullname", "balance", "mobile", "email",
			"idcard_number", "bank_number", "reg_time", "deleted", "agent_id", "parent_id"}, &model.ListParams{})
		if err != nil {
			if err == pg.ErrNoRows {
				global.Logger.Error("用户下级用户不存在：" + err.Error())
				return false
			} else {
				global.Logger.Error("查询用户下级用户出错：" + err.Error())
				return false
			}
		}
		if len(res) == 0 {
			return ""
		}
		//把自己从下级用户中剔除
		var newUser []model.User
		for _, v := range res {
			if v.ID != ID {
				newUser = append(newUser, v)
			}
		}
		return &newUser

	}
	return ""
}

//玄缈代付，发起请求
func PostXuanDaiFu(order *model.WithdrawOrder) map[string]interface{} {
	response := make(map[string]interface{})

	queryUrl := global.Config.Section("xuan").Key("withdrawUrl").String() //实时代付地址
	plat_key := global.Config.Section("xuan").Key("w_plat_key").String()  //平台私钥
	plat_code := global.Config.Section("xuan").Key("plat_code").String()  //平台code
	//定义需要请求的报文字典
	postData := make(map[string]string)
	postData["platcode"] = plat_code //平台code
	postData["out_sn"] = strconv.FormatInt(order.ID, 10)
	postData["head_bank_name"] = order.BankName
	postData["account_name"] = order.Name
	postData["account_type"] = "对私"
	postData["card_type"] = "储蓄卡"
	postData["account_no"] = order.BankNumber
	postData["amt"] = strconv.FormatInt(order.Amount, 10)

	//排序
	var ss []string
	for k, _ := range postData {
		ss = append(ss, k)
	}
	sort.Strings(ss)
	//拼接需要加密的字段字符串
	var signStr string
	for _, v := range ss {
		for key, value := range postData {
			if v != "sign" && v == key {
				signStr = signStr + v + "=" + value + "&"
			}
		}
	}
	signStr = signStr + "key=" + plat_key
	//MD5 加密
	h := md5.New()
	h.Write([]byte(signStr))
	postData["sign"] = strings.ToUpper(hex.EncodeToString(h.Sum(nil)))

	//发送post请求
	req := httplib.Post(queryUrl)
	req.Param("platcode", postData["platcode"])
	req.Param("out_sn", postData["out_sn"])
	req.Param("head_bank_name", postData["head_bank_name"])
	req.Param("account_name", postData["account_name"])
	req.Param("account_type", postData["account_type"])
	req.Param("card_type", postData["card_type"])
	req.Param("account_no", postData["account_no"])
	req.Param("amt", postData["amt"])
	req.Param("sign", postData["sign"])

	//获取玄缈代付结果
	var result WithdrawReturn
	req.ToJSON(&result)
	//如果状态码为 0000 ，表示发送请求成功
	if result.Respcd != "0000" {
		response["status"] = false
		response["msg"] = result.Respmsg
		return response
	}
	response["status"] = true
	return response

}

//玄缈代付，发起查询
func QueryXuanDaiFu(order *model.WithdrawOrder) map[string]interface{} {
	response := make(map[string]interface{})
	queryUrl := global.Config.Section("xuan").Key("queryUrl").String()   //代付状态查询地址
	plat_key := global.Config.Section("xuan").Key("w_plat_key").String() //平台私钥
	plat_code := global.Config.Section("xuan").Key("plat_code").String() //平台code
	//发送查询请求
	postData := make(map[string]string)
	postData["platcode"] = plat_code
	postData["out_sn"] = strconv.FormatInt(order.ID, 10)
	//排序
	var ss []string
	for k, _ := range postData {
		ss = append(ss, k)
	}
	sort.Strings(ss)
	//拼接需要加密的字段字符串
	var signStr string
	for _, v := range ss {
		for key, value := range postData {
			if v != "sign" && v == key {
				signStr = signStr + v + "=" + value + "&"
			}
		}
	}
	signStr = signStr + "key=" + plat_key
	//MD5 加密
	h := md5.New()
	h.Write([]byte(signStr))
	postData["sign"] = strings.ToUpper(hex.EncodeToString(h.Sum(nil)))

	//发送post请求
	req := httplib.Post(queryUrl)
	req.Param("platcode", postData["platcode"])
	req.Param("out_sn", postData["out_sn"])
	req.Param("sign", postData["sign"])

	//玄缈代付结果查询返回内容
	var result WithdrawQuery
	req.ToJSON(&result)
	response["resp_cd"] = result.Respcd
	response["status"] = result.Data.CashStatus
	response["msg"] = result.Respmsg
	return response
}

//杉德代付
//func SandDaiFu(order *model.WithdrawOrder) {
//	queryUrl := global.Config.Section("sand").Key("withdrawUrl").String()
//	mid := global.Config.Section("sand").Key("mid").String()
//	tranCode := "RTPM"  //交易码。RTPM 为实时代付
//	merId = mid  //商户号
//	version := "01"  //版本号
//	productId := "00000004"  //产品ID
//	tm := time.Unix(order.StartTime, 0)
//	tranTime := tm.Format("20060102150405")
//	orderCode := order.ID  //订单号
//	timeOut := ""  //订单超时时间
//	tranAmt := order.Amount//单位为分
//	currencyCode := "156"  //货币种类
//	accAttr := 0 //账户属性。默认为0，对私
//	accType := 4  //账号类型，4表示银行卡
//	accNo := order.BankNumber  //银行卡号
//	accName := order.Name  //账户名
//	provNo := ""   //省份编码
//	cityNo := ""	//城市编码
//	bankName := ""  //银行名称
//	bankType := ""  //银行类型
//	remark := "用户提现"
//
//}
